package puzfun.tow.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.Map.Entry;

public class DatabaseAccess {
	private Connection con;
	private String dadabasename;
	private String username;
	private String password;
	private Statement stmt;       
	private ResultSet res;
	
	public void setDadabaseName(String strDadabaseName) {
		this.dadabasename = strDadabaseName;
	}

	public void setUserName(String strUser) {
		this.username = strUser;
	}

	public void setPassword(String strPassword) {
		this.password = strPassword;
	}

	public void connectToDatabase(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			System.out.println("Load jdbc class fail");
		}
		
		try {
			con=DriverManager.getConnection(dadabasename,username,password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("Connect database fail");
		}
	}
	
	public void readTableToBuffer(String strTableName) throws SQLException{
		stmt = con.createStatement();
		res = stmt.executeQuery("select * from "+strTableName);
	}
	
	public boolean nextIndex() throws SQLException{
		return res.next();
	}
	
	public void getMapFromBuffer(Map<String, String> m) throws SQLException{
		ResultSetMetaData meta_data = res.getMetaData();
        for (int i_col = 1; i_col <= meta_data.getColumnCount(); i_col++) {
            m.put(meta_data.getColumnLabel(i_col), res.getString(i_col));
        }
	}
	
	public boolean getMapFromDatabase(String tableName,String idName,int id,Map<String, String> m){
		boolean res;
		
		try {
			Statement tmpStmt = con.createStatement();
			ResultSet tmpRes = tmpStmt.executeQuery("select * from "+tableName+" where "+idName+"="+id);
			if(tmpRes.next()){
				ResultSetMetaData meta_data = tmpRes.getMetaData();
				for (int i_col = 1; i_col <= meta_data.getColumnCount(); i_col++) {
					m.put(meta_data.getColumnLabel(i_col), tmpRes.getString(i_col));
				}
				res=true;
			}
			else
			{
				System.out.println("no data found when get map from table "+tableName+" where "+idName+"="+id);
				res=false;
			}
			tmpStmt.close();
			tmpRes.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("error when get map from table "+tableName+" where "+idName+"="+id);
			res=false;
		}
		
		return res;
	}
	
	public void clearTableBuffer(){
		try {
			stmt.close();
			res.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void disconnectDatabase(){
		try {
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
